package sk.naive.talker.command;

import sk.naive.talker.message.Category;
import sk.naive.talker.message.DefaultMessageFactory;
import sk.naive.talker.*;
import sk.naive.talker.props.PropertyStoreException;

import java.rmi.RemoteException;

/**
 * @author <a href="mailto:rytier@naive.deepblue.sk">Martin "Rytier" Kerni</a>
 * @version $Revision: 1.10 $ $Date: 2005/01/19 22:41:27 $
 */
public class Topic extends OptionalParameterCommand {
	public static final int MAX_LENGTH = 64;

	protected void execWithoutParameter() throws RemoteException {
		Location loc = new LocationHelper(commandDispatcher).locationForUser(user);
		String topic = loc.getTopic();
		if (topic != null) {
			User topicAuthor = commandDispatcher.getUserFinder().findUserById(loc.getTopicAuthorId());
			ctxSet(DefaultMessageFactory.CTXKEY_VAL, topic);
			if (topicAuthor != null) {
				ctxSet(DefaultMessageFactory.CTXKEY_VAL + "TopicAuthor", topicAuthor.getProperties());
			}
			sendHelper().sendMessage(user, "topic.is");
		} else {
			sendHelper().sendMessage(user, "topic.noTopic");
		}
	}

	protected void execWithParameter() throws RemoteException, CommandException {
		if (params.length() > MAX_LENGTH) {
			sendHelper().sendMessage(user, "topic.tooLong");
			return;
		}
		Location loc = new LocationHelper(commandDispatcher).locationForUser(user);
		try {
			if (params.equalsIgnoreCase("cancel")) {
				loc.set(Location.LPROP_TOPIC, null);
				loc.set(Location.LPROP_TOPIC_AUTHOR, null);
				sendHelper().sendLocal(user, "topic.cancelYou", "topic.cancelAudience", Category.LOCAL);
			} else {
				loc.set(Location.LPROP_TOPIC, params);
				loc.set(Location.LPROP_TOPIC_AUTHOR, user.getId());
				ctxSet(DefaultMessageFactory.CTXKEY_VAL, params);
				sendHelper().sendLocal(user, "topic.you", "topic.audience", Category.LOCAL);
			}
		} catch (PropertyStoreException e) {
			throw new CommandException(e);
		}
	}
}

